import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fstudy/src/common/global.dart';
import 'package:fstudy/src/common/helper.dart';
import 'package:fstudy/src/common/log.dart';
import 'package:fstudy/src/presentation/pages/chat/chat.dart';
import 'package:fstudy/src/presentation/providers/dify.dart';
// ignore: unused_import
import 'package:gpt_markdown/custom_widgets/markdown_config.dart';
import 'package:gpt_markdown/gpt_markdown.dart';
import 'package:provider/provider.dart';

import '../../data/models/chat.dart';

class ChatState extends ConsumerState<ChatPage> {
  final TextEditingController _controller = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  var log = Log.getLogger('');

  // 聊天记录
  final List<Message> _messages = [];
  bool _isLoading = false;
  String _taskId = ""; // 任务ID 用于请求跟踪和下方的停止响应接口

  // 替换为你的DeepSeek API密钥
  String apiKey = '';
  // 服务器地址
  String apiUrl = '';
  // 用户ID，可使用设备Id
  String userId = '';
  String _conversationId = '';

  @override
  void initState() {
    super.initState();
    final conf = Global.config;
    apiKey = conf.aiApiKey;
    apiUrl = conf.aiApiUrl;
    userId = conf.deviceId;
  }

  void _initMessages() async {
    if (_conversationId.isEmpty) {
      setState(() {
        _messages.removeRange(0, _messages.length);
      });
      return;
    }

    final response = await api().get(
      '/messages',
      queryParameters: {
        'conversation_id': _conversationId,
        'user': userId,
        'limit': 100,
      },
    );

    final List<dynamic> items = response.data['data'];
    final List<Message> newMessage = [];
    for (var item in items) {
      newMessage.add(
        Message(
          content: item['query'],
          isUser: true,
          timestamp: DateTime.fromMillisecondsSinceEpoch(
            item['created_at'] * 1000,
          ),
        ),
      );
      newMessage.add(
        Message(
          content: item['answer'],
          isUser: false,
          timestamp: DateTime.fromMillisecondsSinceEpoch(
            item['created_at'] * 1000,
          ),
        ),
      );
    }
    setState(() {
      _messages.removeRange(0, _messages.length);
      _messages.addAll(newMessage);
    });
  }

  void _updateConversationId() {
    log.d('_updateConversationId');
    if (_messages.isNotEmpty) {
      _messages.removeRange(0, _messages.length);
    }

    _initMessages();
  }

  @override
  Widget build(BuildContext context) {
    final selected = context.watch<CurrentConversationProvider>();

    if (selected.id != _conversationId) {
      _conversationId = selected.id;
      _updateConversationId();
    }

    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            controller: _scrollController,
            padding: EdgeInsets.all(16),
            itemCount: _messages.length,
            itemBuilder: (context, index) {
              return _buildMessageBubble(_messages[index]);
            },
          ),
        ),
        _buildInputArea(),
      ],
    );
  }

  // 单条消息
  Widget _buildMessageBubble(Message message) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment:
            message.isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!message.isUser) ...[
            CircleAvatar(
              backgroundColor: Colors.blue[100],
              child: Icon(Icons.smart_toy, color: Colors.blue[700]),
            ),
            SizedBox(width: 8),
          ],
          Flexible(
            child: Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: message.isUser ? Colors.blue[500] : Colors.grey[200],
                borderRadius: BorderRadius.circular(16),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (message.isUser)
                    Text(
                      message.content,
                      style: TextStyle(color: Colors.white, fontSize: 16),
                    )
                  else
                    _buildMarkdownContent(message),
                  if (message.isStreaming)
                    Container(
                      margin: EdgeInsets.only(top: 4),
                      child: SizedBox(
                        height: 12,
                        width: 12,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(
                            message.isUser ? Colors.white : Colors.blue,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
          if (message.isUser) ...[
            SizedBox(width: 8),
            CircleAvatar(
              backgroundColor: Colors.green[100],
              child: Icon(Icons.person, color: Colors.green[700]),
            ),
          ],
        ],
      ),
    );
  }

  // Markdown内容
  Widget _buildMarkdownContent(Message message) {
    return GptMarkdown(
      message.content.isEmpty ? '正在思考中...' : message.content,
      style: TextStyle(color: Colors.black87, fontSize: 16, height: 1.4),
      codeBuilder: _buildCodeElement,
    );
  }

  // 代码块
  Widget _buildCodeElement(
    BuildContext context,
    String name,
    String code,
    bool closed,
  ) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 8),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[700]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 代码块头部
          Container(
            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8),
                topRight: Radius.circular(8),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'code',
                  style: TextStyle(
                    color: Colors.grey[300],
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                GestureDetector(
                  onTap: () => _copyToClipboard(code),
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.blue[600],
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.copy, size: 12, color: Colors.white),
                        SizedBox(width: 4),
                        Text(
                          '复制',
                          style: TextStyle(color: Colors.white, fontSize: 10),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 代码内容
          Container(
            padding: EdgeInsets.all(12),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: SelectableText(
                code,
                style: TextStyle(
                  color: Colors.green[300],
                  fontSize: 14,
                  fontFamily: 'monospace',
                  height: 1.4,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 复制到剪贴板
  void _copyToClipboard(String text) {
    Clipboard.setData(ClipboardData(text: text));
  }

  // 输入框
  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            offset: Offset(0, -2),
            blurRadius: 6,
            color: Colors.black12,
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _controller,
              decoration: InputDecoration(
                hintText: '输入你的消息...',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(24),
                ),
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
              ),
              maxLines: null,
              textInputAction: TextInputAction.send,
              onSubmitted: _isLoading ? null : (_) => _sendMessage(),
            ),
          ),
          SizedBox(width: 8),
          FloatingActionButton(
            onPressed: _isLoading ? _stopResponse : _sendMessage, // 可添加停止响应的操作
            mini: true,
            child:
                _isLoading
                    ? SizedBox(
                      height: 20,
                      width: 20,
                      child: Center(
                        child: Stack(
                          alignment: Alignment.center,
                          children: [
                            CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                Colors.white,
                              ),
                            ),
                            Icon(Icons.square, size: 14, color: Colors.red),
                          ],
                        ),
                      ),
                    )
                    : Icon(Icons.send),
          ),
        ],
      ),
    );
  }

  void _sendMessage() async {
    if (_controller.text.trim().isEmpty) return;

    final userMessage = _controller.text.trim();
    _controller.clear();

    setState(() {
      _messages.add(
        Message(content: userMessage, isUser: true, timestamp: DateTime.now()),
      );
      _isLoading = true;
    });

    _scrollToBottom();

    // 创建AI消息占位符
    final aiMessageIndex = _messages.length;
    setState(() {
      _messages.add(
        Message(
          content: '',
          isUser: false,
          timestamp: DateTime.now(),
          isStreaming: true,
        ),
      );
    });

    try {
      await _streamResponse(userMessage, aiMessageIndex);
    } catch (e) {
      setState(() {
        _messages[aiMessageIndex] = Message(
          content: '抱歉，发生了错误：$e',
          isUser: false,
          timestamp: DateTime.now(),
        );
        _isLoading = false;
      });
    }
  }

  void _stopResponse() async {
    if (_taskId.isEmpty) return;
    if (!_isLoading) return;

    final requestBody = {'user': userId};

    final response = await api().post(
      '/chat-messages/$_taskId/stop',
      data: requestBody,
      options: Options(responseType: ResponseType.stream),
    );

    if (response.statusCode != 200) {
      throw Exception('API请求失败: ${response.statusCode}');
    }

    setState(() {
      _isLoading = false;
    });
  }

  Future<void> _streamResponse(String userMessage, int messageIndex) async {
    final messages =
        _messages
            .where((msg) => !msg.isStreaming)
            .map(
              (msg) => {
                'role': msg.isUser ? 'user' : 'assistant',
                'content': msg.content,
              },
            )
            .toList();

    // 添加当前用户消息
    messages.add({'role': 'user', 'content': userMessage});

    final requestBody = {
      'query': userMessage,
      'inputs': {},
      'response_mode': 'streaming',
      'conversation_id': _conversationId,
      'user': userId,
    };

    final response = await api().post(
      '/chat-messages',
      data: requestBody,
      options: Options(responseType: ResponseType.stream),
    );
    StreamTransformer<Uint8List, List<int>> unit8Transformer =
        StreamTransformer.fromHandlers(
          handleData: (data, sink) {
            sink.add(List<int>.from(data));
          },
        );

    if (response.statusCode != 200) {
      throw Exception('API请求失败: ${response.statusCode}');
    }

    String accumulatedContent = '';

    String newConversationId = '';

    await for (var chunk in response.data.stream
        .transform(unit8Transformer)
        .transform(const Utf8Decoder())
        .transform(const LineSplitter())) {
      log.d('chunk is $chunk');
      if (chunk.isEmpty || !chunk.startsWith('data: ')) {
        log.i('chunk is empty');
        continue;
      }

      final dataContent = chunk.substring(6);

      if (dataContent == '[DONE]') {
        log.i('chunk is done');
        break;
      }

      try {
        final data = json.decode(dataContent);
        if (data['event'] == 'message_end') break;
        if (data['event'] == 'message') {
          accumulatedContent += data['answer'];
          setState(() {
            _messages[messageIndex] = Message(
              content: accumulatedContent,
              isUser: false,
              timestamp: DateTime.now(),
              isStreaming: true,
            );
          });
          if (_conversationId.isEmpty && newConversationId.isEmpty) {
            newConversationId = data['conversation_id'];
          }
          _taskId = data['task_id'];

          _scrollToBottom();
        } else {
          continue;
        }
      } catch (e) {
        //print('解析响应时出错: $e');
        continue;
      }
    }
    _taskId = ""; // 重置taskId

    if (newConversationId.isNotEmpty && mounted) {
      // 重置会话ID
      context.read<CurrentConversationProvider>().change(newConversationId);

      // 重置会话列表（更新会话标题）
      await context.read<ConversationItemsProvider>().reset(null);
    }

    // 确保最终状态正确
    setState(() {
      if (messageIndex < _messages.length) {
        _messages[messageIndex] = Message(
          content: accumulatedContent.isEmpty ? '无响应内容' : accumulatedContent,
          isUser: false,
          timestamp: DateTime.now(),
          isStreaming: false,
        );
      }
      _isLoading = false;
    });
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _scrollController.dispose();
    super.dispose();
  }
}
